package com.excu.factory.connection.heat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;

public class InterfaceClient {
    private final String serverIp;
    private final int serverPort;
    private SocketChannel socketChannel;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
    private final ExecutorService readerExecutor = Executors.newSingleThreadExecutor(r -> {
        Thread thread = new Thread(r, "client-reader");
        thread.setDaemon(true);
        return thread;
    });
    private volatile boolean isRunning = true;
    private volatile boolean isConnected = false;

    // 服务器支持的接口常量
    public static final String INTERFACE_USER = "/api/user";
    public static final String INTERFACE_ORDER = "/api/order";
    public static final String INTERFACE_PRODUCT = "/api/product";

    public InterfaceClient(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    // 启动客户端
    public void start() {
        System.out.println("客户端启动，尝试连接到服务器: " + serverIp + ":" + serverPort);
        connect();
        showInterfaceMenu();
    }

    // 连接服务器
    private void connect() {
        try {
            // 关闭现有连接
            if (socketChannel != null) {
                socketChannel.close();
            }

            // 建立新连接
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress(serverIp, serverPort));

            // 等待连接完成
            while (!socketChannel.finishConnect()) {
                Thread.sleep(100);
            }

            System.out.println("成功连接到服务器");
            isConnected = true;

            // 启动消息读取和心跳
            startMessageReader();
            startHeartbeat();

        } catch (Exception e) {
            System.err.println("连接服务器失败: " + e.getMessage());
            isConnected = false;
        }
    }

    // 显示接口菜单
    private void showInterfaceMenu() {
        new Thread(() -> {
            System.out.println("\n===== 服务器接口列表 =====");
            System.out.println("1. " + INTERFACE_USER + " - 用户信息接口 (参数: userId)");
            System.out.println("2. " + INTERFACE_ORDER + " - 订单接口 (参数: orderId)");
            System.out.println("3. " + INTERFACE_PRODUCT + " - 产品接口 (参数: productId)");
            System.out.println("输入格式示例: " + INTERFACE_USER + "?userId=1001");
            System.out.println("输入exit退出客户端");
            System.out.println("==========================");
            promptInterfaceInput();
        }).start();
    }

    // 提示用户输入接口请求
    private void promptInterfaceInput() {
        InputStream in = System.in;
        BufferedReader consoleReader = new BufferedReader(new InputStreamReader(in));
        System.out.print("\n请输入接口请求: ");
        
        try {
            String input = consoleReader.readLine();
            if (input == null || input.trim().isEmpty()) {
                promptInterfaceInput();
                return;
            }

            if (input.equalsIgnoreCase("exit")) {
                stop();
                return;
            }

            // 检查是否是有效的接口请求格式
            if (input.startsWith(INTERFACE_USER) || 
                input.startsWith(INTERFACE_ORDER) || 
                input.startsWith(INTERFACE_PRODUCT)) {
                
                if (isConnected) {
                    sendInterfaceRequest(input);
                } else {
                    System.out.println("未连接到服务器，尝试重新连接...");
                    connect();
                    Thread.sleep(1000);
                    if (isConnected) {
                        sendInterfaceRequest(input);
                    } else {
                        System.out.println("连接失败，请稍后再试");
                    }
                }
            } else {
                System.out.println("无效的接口，请使用支持的接口");
            }
            
            promptInterfaceInput();
            
        } catch (Exception e) {
            e.printStackTrace();
            promptInterfaceInput();
        }
    }

    // 发送接口请求
    private void sendInterfaceRequest(String request) throws IOException {
        if (socketChannel == null || !socketChannel.isOpen()) {
            System.out.println("连接已关闭");
            return;
        }
        
        ByteBuffer buffer = ByteBuffer.wrap((request + "\n").getBytes(StandardCharsets.UTF_8));
        socketChannel.write(buffer);
        System.out.println("已发送请求: " + request);
    }

    // 启动消息读取
    private void startMessageReader() {
        readerExecutor.submit(() -> {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (isRunning && socketChannel != null && socketChannel.isOpen()) {
                try {
                    int bytesRead = socketChannel.read(buffer);
                    if (bytesRead > 0) {
                        buffer.flip();
                        String response = StandardCharsets.UTF_8.decode(buffer).toString().trim();
                        System.out.println("\n接口响应: " + response);
                        buffer.clear();
                        System.out.print("请输入接口请求: ");
                    } else if (bytesRead == -1) {
                        // 服务器断开连接
                        System.err.println("\n服务器已断开连接");
                        isConnected = false;
                        connect(); // 尝试重连
                        break;
                    }
                } catch (IOException e) {
                    System.err.println("\n读取响应异常: " + e.getMessage());
                    isConnected = false;
                    break;
                }
            }
        });
    }

    // 启动心跳保持连接
    private void startHeartbeat() {
        scheduler.scheduleAtFixedRate(() -> {
            if (isConnected && socketChannel != null && socketChannel.isOpen()) {
                try {
                    ByteBuffer buffer = ByteBuffer.wrap("HEARTBEAT\n".getBytes(StandardCharsets.UTF_8));
                    socketChannel.write(buffer);
                } catch (IOException e) {
                    System.err.println("心跳发送失败，连接可能已断开");
                    isConnected = false;
                }
            }
        }, 10, 30, TimeUnit.SECONDS); // 每30秒发送一次心跳
    }

    // 停止客户端
    public void stop() {
        isRunning = false;
        isConnected = false;
        try {
            if (socketChannel != null) {
                socketChannel.close();
            }
            scheduler.shutdown();
            readerExecutor.shutdown();
            System.out.println("客户端已退出");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 连接到指定服务器
        InterfaceClient client = new InterfaceClient("localhost", 9000);
        client.start();
    }
}
